"""Reminder scheduler service for automatic follow-up reminders."""

from __future__ import annotations

import logging
from datetime import datetime
from sqlalchemy.orm import Session

from ..repositories.follow_up_reminder_repository import FollowUpReminderRepository
from ..services.email_service import EmailService
from ..core.config import settings

logger = logging.getLogger(__name__)


class ReminderSchedulerService:
    """提醒调度服务（自动检测并发送邮件）."""

    def __init__(self, db: Session, email_service: EmailService):
        """
        Initialize reminder scheduler service.

        Args:
            db: Database session
            email_service: Email service for sending notifications
        """
        self.db = db
        self.email_service = email_service
        self.reminder_repo = FollowUpReminderRepository(db)

    def check_and_send_reminders(self) -> dict:
        """
        检查并发送到期提醒（定时任务调用）.

        Returns:
            dict: 发送结果统计
        """
        logger.info("Starting reminder check...")

        # 1. 获取需要发送的提醒
        pending_reminders = self.reminder_repo.get_pending_reminders_to_send()

        if not pending_reminders:
            logger.info("No pending reminders to send")
            return {"total": 0, "success": 0, "failed": 0}

        logger.info(f"Found {len(pending_reminders)} reminders to send")

        success_count = 0
        failed_count = 0

        # 2. 逐个发送邮件
        for reminder in pending_reminders:
            try:
                # 发送邮件
                self._send_reminder_email(reminder)

                # 标记为已发送
                self.reminder_repo.mark_as_sent(reminder.id)
                success_count += 1

                logger.info(f"Reminder {reminder.id} sent successfully to {reminder.assignee.email}")

            except Exception as e:
                failed_count += 1
                logger.error(f"Failed to send reminder {reminder.id}: {str(e)}")
                continue

        # 3. 提交事务
        self.db.commit()

        result = {
            "total": len(pending_reminders),
            "success": success_count,
            "failed": failed_count,
            "timestamp": datetime.now().isoformat()
        }

        logger.info(f"Reminder check completed: {result}")
        return result

    def _send_reminder_email(self, reminder) -> None:
        """
        发送提醒邮件.

        Args:
            reminder: FollowUpReminder对象
        """
        # 构建邮件主题
        subject = f"[跟进提醒] {reminder.lead.name} - {reminder.trigger_reason}"

        # 构建邮件正文
        assignee_name = reminder.assignee.full_name or reminder.assignee.email.split('@')[0]
        body = f"""
您好 {assignee_name}，

这是一条自动跟进提醒：

【客户信息】
- 姓名：{reminder.lead.name}
- 手机：{reminder.lead.phone}
- 需求：{reminder.lead.demand_type.value}
- 预算：{reminder.lead.budget_range or '未填写'}
- 阶段：{reminder.lead.stage.value}

【提醒信息】
- 提醒类型：{'自动提醒' if reminder.reminder_type == 'auto' else '手动提醒'}
- 触发原因：{reminder.trigger_reason or '无'}
- 提醒时间：{reminder.reminder_time.strftime('%Y-%m-%d %H:%M')}

【备注】
{reminder.notes or '无'}

---
请及时登录CRM系统跟进客户，标记任务完成。

系统登录地址：{settings.FRONTEND_BASE_URL or 'http://localhost:5173'}

此邮件由系统自动发送，请勿回复。
        """.strip()

        # 发送邮件（同步调用）
        self.email_service.send_email(
            email_to=reminder.assignee.email,
            subject=subject,
            body=body
        )
